#!/usr/bin/python3
import sys
import os
import subprocess
linking = '-c' not in sys.argv and '-S' not in sys.argv and '-E' not in sys.argv
args = sys.argv[1:]

# we use the default instruction threshold, pass -fxray-instruction-threshold=N to override
args += '-g -pthread -fxray-instrument'.split()
if linking:
    srcdir = os.path.dirname(os.path.dirname(__file__))
    args += [f'-B{srcdir}/compiler-wrappers/xray'] # use our ld wrapper to override __xray_Function* handlers

    is_shared = '-shared' in args
    if not is_shared: # don't link the runtime into .so's - only into the executables using them
        args += [os.path.join(srcdir, f) for f in ['funtrace.cpp', 'funtrace_pg.S']] + [f'-Wl,--dynamic-list={srcdir}/funtrace.dyn']
        args += ['-ldl']
    else:
        args += ['-fxray-shared','fun_xray_so.S'] # this requires a pretty new version of LLVM; older ones can't instrument inside shared objects
        # remove no-undefined for access to the funtrace_* runtime functions
        args = [a for a in args if a != '-Wl,--no-undefined']

# currently funtrace++ doesn't support filtering of XRay compiler output so we run clang++ directly
clangpath = subprocess.getoutput('which clang++')
os.execl(clangpath, *([clangpath] + [arg for arg in args if not arg.startswith('-funtrace')]))
